/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "interceptor.h"
#include "imageknife_task_internal.h"
#include "log.h"
#include <chrono>
namespace ImageKnifePro {

bool Interceptor::Process(std::shared_ptr<ImageKnifeTask> task)
{
    IMAGE_KNIFE_CHECK_RETURN(task == nullptr, false);
    auto taskInternal = std::dynamic_pointer_cast<ImageKnifeTaskInternal>(task);
    IMAGE_KNIFE_CHECK_RETURN(taskInternal == nullptr, false);

    if (taskInternal->IsFatalErrorHappened()) {
        return false;
    }
    taskInternal->SetInterceptor(this);

    std::string info = ImageKnifeTaskInternal::GetTaskInfo(task->GetImageRequestType(),
                                                           taskInternal->GetImageKnifeRequestInternal());
    std::string cacheInfo;
    if (task->cacheTask.type != CacheTaskType::NONE) {
        cacheInfo = "CacheTask Type:" + std::to_string((int)task->cacheTask.type);
    }
    IMAGE_KNIFE_LOG(LOG_DEBUG, "%{public}s %{public}s %{public}s Start", info.c_str(), name.c_str(), cacheInfo.c_str());

    auto start = std::chrono::high_resolution_clock::now();
    if (Resolve(task)) {
        auto end = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
        IMAGE_KNIFE_LOG(LOG_DEBUG, "%{public}s [%{public}lld] %{public}s %{public}s Finished",
                        info.c_str(), duration.count(), name.c_str(), cacheInfo.c_str());
        taskInternal->ClearInterceptorPtr();
        return true;
    } else if (next_ != nullptr) {
        return next_->Process(task);
    } else {
        taskInternal->ClearInterceptorPtr();
        return false;
    }
}

void Interceptor::Cancel(std::shared_ptr<ImageKnifeTask> task)
{
}

void MemoryCacheInterceptor::SetNext(std::shared_ptr<MemoryCacheInterceptor> interceptor)
{
    next_ = interceptor;
}

void FileCacheInterceptor::SetNext(std::shared_ptr<FileCacheInterceptor> interceptor)
{
    next_ = interceptor;
}

void LoadInterceptor::SetNext(std::shared_ptr<LoadInterceptor> interceptor)
{
    next_ = interceptor;
}

void DecodeInterceptor::SetNext(std::shared_ptr<DecodeInterceptor> interceptor)
{
    next_ = interceptor;
}
} // end of namespace
